<!DOCTYPE html>
<html>
<head>
  <title>Decimal to Binary Conversion</title>
  <style>
    #result {
      font-family: monospace;
    }

    table {
            border-collapse: collapse;
        }
        th, td {
            border: 1px solid black;
            padding: 5px;
        }
  </style>
</head>
<body>
  <h1>Decimal to Binary Conversion</h1>
  <label>Enter a decimal number:</label>
  <input type="number" id="decimalInput" value="114514">
  <button onclick="convertToBinary()">Convert</button>

  <div>
    从下到上 从左边到右边
  </div>
  <div id="result"></div>

  <!-- <script src="script.js"></script> -->

  <table>
    <tr>
        <th>n</th>
        <th>Binary</th>
        <th>Hexadecimal</th>
        <th>Decimal</th>
    </tr>
    <script>
        for (let n = 1; n <= 9; n++) {
            const value = Math.pow(2, n);
            const binary = value.toString(2);
            const hexadecimal = value.toString(16);
            const decimal = value.toString(10);
            
            document.write(`
                <tr>
                    <td>${n}</td>
                    <td>${binary}</td>
                    <td>${hexadecimal}</td>
                    <td>${decimal}</td>
                </tr>
            `);
        }
    </script>
</table>

  <script>
    function insertSpaces(str) {
  // 使用正则表达式将每隔四个字符插入一个空格
  const spacedString = str.replace(/(.{4})/g, '$1 ');

  // 移除字符串末尾可能的额外空格
  const finalString = spacedString.trim();

  return finalString;
}

// // 示例用法
// const inputString = "1234567890123456";
// const result = insertSpaces(inputString);
// console.log(result); // 输出 "1234 5678 9012 3456"


    function convertToBinary() {
  var decimalInput = document.getElementById('decimalInput');
  var decimal = Number(decimalInput.value);
  var binary = ''; // 初始化二进制字符串

  var steps = ''; // 用于存储转换过程的字符串

  if (decimal === 0) {
    binary = '0';
  } else {
    while (decimal > 0) {
      var remainder = decimal % 2; // 计算余数
      binary = remainder + binary; // 将余数添加到二进制字符串的前面
      steps += decimal + ' ÷ 2 = ' + Math.floor(decimal / 2) + '，余数为 ' + remainder + '<br>';
      decimal = Math.floor(decimal / 2); // 更新数字为商
    }
  }

  var result = document.getElementById('result');
 let  binary_insertSpaces= insertSpaces(binary)
  result.innerHTML = '<h3>Conversion Steps:</h3>' + steps + '<h3>Binary Representation:</h3>' + binary_insertSpaces;
}


  </script>
</body>
</html>
